#! /usr/bin/env python3

import sys
import os
import re
import shutil


g_filedict = {} # 字典, {'filename(session)': fp}

def append(filename, linedata):
    if filename not in g_filedict:
        fp = open(filename, 'w')
        g_filedict.update({filename: fp})
    else:
        fp = g_filedict[filename]
        fp.write(linedata)


def get_format_by_fwlog(sess):
    pass


def forcc_to_human_codec(i4cc, o4cc):
    bitstream = ['H264', 'H265', 'JPEG']
    frame = ['NV12']

    ihex = bytes.fromhex(i4cc)
    ohex = bytes.fromhex(o4cc)
    ifmt = ihex.decode()
    ofmt = ohex.decode()
    ifmt = ifmt[::-1]
    ofmt = ofmt[::-1]

    codec = 'UNKNOW'
    if ifmt in bitstream:
        codec = ifmt + 'DEC'
    elif ifmt in frame:
        codec = ofmt + 'ENC'
    else:
        print(f'unknow input format: {ifmt}, with output format: {ofmt}')

    return codec;


# input: single session file
def get_format_by_syslog(sess):
    ifmt = ''
    ofmt = ''
    with open(sess) as f:
        line_limit = 100 # 100行内，应该出现set format相关
        i = 0
        for line in f: # 迭代器，对比readlines，大文件内存友好
            i += 1
            if 'Set format. type=10' in line or 'Set format. type=2' in line:
                ifmt = line
                continue
            if 'Set format. type=9' in line or 'Set format. type=1' in line:
                ofmt = line
                continue
            if i > line_limit:
                break
    
    pattern = r'pixelformat=0x(.*), width'
    match = re.search(pattern, ifmt)
    if match:
        ifmt = match.group(1)
    match = re.search(pattern, ofmt)
    if match:
        ofmt = match.group(1)

    return forcc_to_human_codec(ifmt, ofmt)


def rename_sessions(outpath):
    files = os.listdir(outpath)
    i = 0
    for sess in files:
        name = outpath + sess
        fmt = get_format_by_syslog(name)
        #print(f'{sess}: {fmt}')

        new_name = name + '-' + fmt
        os.rename(name, new_name)
        i += 1
        print(f'{i} -> {new_name}')
    pass


def divide_syslog(log, outpath):
    if os.path.exists(outpath):
        shutil.rmtree(outpath)
    # 创建新目录
    os.makedirs(outpath)

    with open(log) as f:
        for line in f: # 迭代器，对比readlines，大文件内存友好
            if 'MVX session:' in line:
                word = line.split()
                i = word.index('session:') # 找到`session:`的下一个元组
                if i < len(word) - 1:
                    sess = word[i + 1]
                    append(outpath + sess, line)
    # XXX
    rename_sessions(outpath)


# #################################################################################

if len(sys.argv) != 2:
    print('Please input one syslog/dmesg.')
    exit(1)


log = sys.argv[1]
out_drv = 'output-drv/'
out_fw  = 'output-fw/'

divide_syslog(log, out_drv)

